import { mapState } from "vuex"
import { getSelectFilterFieldListOptions } from "../../../lib/table"
import { getChartAxisData, getFieldListByComponentList, createGroupOption, getFieldListByDimensionsAndMeasures, getTableField } from "../../../lib/analysisData"
import { getDashboardAndCategoryTreeByType } from "@/api/dashboard/board"
import "./index.less"
import MultipleFieldSelect from "../../../../common/MultipleFieldSelect"
import { deepCopy } from "../../../lib/utils"

// 编辑状态下:设置当前组件的源字段.选择目标页面,选择跳转页面的(多个)目标组件的某个字段
// 预览状态下:点击业务组件时,获取当前组件的源字段的数据,跳转,并将复制源字段的数据(值)赋值给跳转页面多个组件的某个字段

export default {
  data () {
    return {
      customFormJson: [],
      targetTypeOptions: [
        {
          label: '看板',
          value: 'board'
        },
        {
          label: '链接',
          value: 'link'
        }
      ],
      targetPageOptions: [],
      openTypeOptions: [
        {
          label: '新窗口',
          value: 'target'
        },
        {
          label: '当前窗口',
          value: 'self'
        },
      ],
      // sourceOptions: [],
      targetOptions: [],
      targetDefaultOptions: []
    }
  },
  methods: {

    renderTree (list) {
      return list.map(item => this.renderTreeItem(item))
    },
    renderTreeItem (treeNode) {
      const { id, name, children, treeObj = [] } = treeNode
      return (
        <a-tree-select-node
          selectable={false}
          key={`parent-${id}`}
          value={`parent-${id}`}
          title={name}>
          {
            children.map(item => this.renderTreeItem(item))
          }
          {
            (treeObj || []).map(item => this.renderBoardItem(item))
          }
        </a-tree-select-node>
      )
    },
    renderBoardItem (board) {
      const { id, name, itemList } = board
      return (
        <a-tree-select-node
          key={`child-${id}`}
          value={id}
          componentList={itemList}
          title={name}>
        </a-tree-select-node>
      )
    },
    handleTargetPageChange (value, label, option) {
      // console.log(value, label, option)
      if (!value) {
        this.targetOptions = []
      } else {
        const {
          componentList
        } = option.triggerNode.$attrs
        this.getTargetOptions(componentList)
      }

      // 重新设置options后,清空value
      this.form.target = []
    },
    filterTargetOptions (groupList, colType) {
      return groupList.map(group => {
        const {
          children
        } = group
        const newChildren = children.filter(item => item.colType === colType)
        return deepCopy({
          ...group,
          children: newChildren
        })
      })
    },
    /**
     * 获取目标字段options
     * @param {*} componentList 组件列表,即itemList
     * @param {string} colType 字段类型,用于过滤
     * @returns
     */
    getTargetOptions (componentList, colType) {
      // getFieldListByComponentList(componentList, true)
      // .then(list => {
      //   this.targetOptions = list
      // })
      const tableCodeList = componentList.map(item => {
        return {
          tableCode: item.tableCode,
          datasourceId: item.datasourceId,
          name: item.name,
          key: item.componentPageId
        }
      })
      Promise.all(tableCodeList.map(getTableField))
      .then(res => {
        const list = []
        res.forEach(item => {
          const {
            dimensions,
            measures
          } = item.data
          const children = getFieldListByDimensionsAndMeasures(dimensions, measures)
          list.push(createGroupOption(item.name, item.key, children))
        })
        this.targetDefaultOptions = list
        this.handleSourceChange(this.form.source, false)
      })
    },
    // 源字段change
    handleSourceChange (source, vnode) {
      if (source) {
        const colType = this.sourceOptions.find(item => item.value === source).colType
        this.targetOptions = this.filterTargetOptions(this.targetDefaultOptions, colType)
      } else {
        this.targetOptions = deepCopy(this.targetDefaultOptions)
      }
      // vnode存在说明不是初始化触发
      if (vnode) {
        // 清空目标字段
        this.form.target = []
      }
    },
    // 目标字段change
    handleTargetChange (target) {
      this.form.target = target
    },
    getData () {
      getDashboardAndCategoryTreeByType()
      .then(data => {
        this.targetPageOptions = data.data
        const selectId = this.form.targetPage
        if (selectId) {
          const each = (list) => {
            for (let i = 0; i < list.length; i++) {
              const element = list[i]
              if (element.treeObj?.length > 0) {
                const treeObj = element.treeObj.find(item => item.id === selectId)
                if (treeObj) {
                  this.getTargetOptions(treeObj.itemList)
                  break
                }
              }
              each(element.children)
            }
          }
          each(this.targetPageOptions)
        }
      })
    }
  },
  components: {
    MultipleFieldSelect
  },
  computed: {
    ...mapState('lowCode', {
      selectedComponent: state => state.selectedComponent,

    }),
    sourceOptions () {
      return this.selectedComponent.props.value.params.dimensions?.map(element => {
        return {
          colType: element.colType,
          label: element.name,
          value: element.enName,
        }
      }) || []
    },
    form () {
      console.log(this.selectedComponent.jump)
      return this.selectedComponent.jump
    }

    // formJson(){
    //   return getAttrList(this.selectedComponent.tag, this.$store.state.lowCode)
    // }
  },
  created () {
    this.getData()
  },
  render () {
    const {
      targetTypeOptions,
      form,
      openTypeOptions,
      renderTree,
      targetPageOptions,
      sourceOptions,
      targetOptions,
      handleSourceChange,
      handleTargetChange,
      handleTargetPageChange
    } = this
    return (
      <div class="jump">
        <a-form ref="ruleForm" class="form" colon={false} v-model={form}>
          <a-form-item
            label="跳转至"
            prop="targetType"
            class="row"
            >
            <a-radio-group name="radioGroup" v-model={form.targetType}>
              {
                targetTypeOptions.map(item => (
                  <a-radio key={item.value} value={item.value}>
                    {item.label}
                  </a-radio>
                ))
              }
            </a-radio-group>
          </a-form-item>
          <a-form-item
            v-show={form.targetType === 'board'}
            label="目标页面"
            prop="targetPage"
            class="row"
            replaceFields={{ children: 'children', title: 'title', key: 'key', value: 'value' }}>
            <a-tree-select allowClear onChange={handleTargetPageChange} v-model={form.targetPage}>
              {renderTree(targetPageOptions)}
            </a-tree-select>
          </a-form-item>
          <a-form-item
            v-show={form.targetType === 'link'}
            label="目标地址"
            prop="targetAddress"
            class="row"
            >
            <a-input v-model={form.targetAddress} />
          </a-form-item>
          <a-form-item
            label="打开位置"
            prop="openType"
            class="row"
            >
            <a-select v-model={form.openType}>
              {
                openTypeOptions.map(option => (
                  <a-select-option key={option.value}>
                    {option.label}
                  </a-select-option>
                ))
              }
            </a-select>
          </a-form-item>

          <a-form-item
            v-show={form.targetType === 'board'}
            label="过滤条件"
            prop="isFilter"
            class="row"
            >
            <a-switch v-model={form.isFilter} />
          </a-form-item>

          <div v-show={form.targetType === 'board' && form.isFilter} >
            <a-form-item
              label="源字段"
              prop="source"
              class="row"
              >
              <a-select v-model={form.source} allowClear onChange={handleSourceChange} >
                {
                  sourceOptions.map(option => (
                    <a-select-option key={option.value}>
                      {option.label}
                    </a-select-option>
                  ))
                }

              </a-select>
            </a-form-item>
            <a-form-item
              label="目标字段"
              prop="target"
              class="row"
              >
              {/* <a-select v-model={form.target} mode="multiple">
                {
                  targetOptions.map(option => (
                    <a-select-option key={option.value}>
                      {option.label}
                    </a-select-option>
                  ))
                }

              </a-select> */}
              <MultipleFieldSelect disabled={!form.source} onChange={handleTargetChange} v-model={form.target} options={targetOptions} isSameField={false} />
            </a-form-item>

          </div>
          <a-form-item
            label="启用跳转设置"
            prop="isEnable"
            class="row"
            >
            <a-switch v-model={form.isEnable} />
          </a-form-item>

        </a-form>
      </div>

    )
  }
}
